<?php

namespace App\Models;


use App\Http\Traits\GlobalConstant;
use Illuminate\Database\Eloquent\SoftDeletes;

class Course extends Orm
{
    use SoftDeletes;
    //
    protected $table = 'course';
//    protected $dateFormat = 'U';
//    public $timestamps = false;
    protected $casts = [
//        'pics' => 'json',
    ];
    protected $dates=['deleted_at'];
    protected $appends = [
        'course_time',
//        'teacher_info'//多个授课老师时加此，且teacher_id改为字符串类型，如1,3
    ];

    public function getTeacherInfoAttribute()
    {
        if ($this->attributes['teacher_id']) {
            $items = explode(',', $this->attributes['teacher_id']);
            if (count($items) > 0) {
                return Teacher::whereIn('id', $items)->get();
            }
        }
        return [];
    }

    public function getCourseTimeAttribute()
    {
        $date = date('Y-m-d', $this->attributes['start_time']);
        return substr($date, 0, 10) . ' ' . GlobalConstant::daysOfWeekCn[date('l', strtotime($date))];
    }

    public function categoryInfo()
    {
        return $this->belongsTo(Category::class, 'type');
    }

    //此处注释是因为用Edit.php文件编辑和新增
//    public function setDiscoverAttribute($value)
//    {
//        $this->dealSetImageAttribute('discover', $value);
//    }

    public function getPicsAttribute()
    {
        return json_decode($this->attributes['pics'], true);
    }

    public function campusInfo()
    {
        return $this->belongsTo(Campus::class, 'campus_id');
    }

    public function getPriceAttribute()
    {
        return $this->attributes['price'] <= 0 ? '免费' : '￥' . $this->attributes['price'];
    }

    public function setStartTimeAttribute($value)
    {
        $this->attributes['start_time'] = strtotime($value);
    }

    public function getStartTimeAttribute()
    {
        return date('Y-m-d', $this->attributes['start_time']);
    }

    public function courseSectionInfo()
    {
        return $this->hasMany(CourseSection::class, 'course_id')->orderBy('serial_number', 'asc');
    }

    public function teacherInfo()
    {
        return $this->hasOne(Teacher::class, 'id', 'teacher_id');
    }

    public function courseSectionCompleteInfo()
    {
        return $this->hasMany(CourseSection::class, 'course_id', 'id')->where('end_time', '<', time());
    }

}
